<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 操作栏 -->
      <el-row>
        <!-- 搜索框 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="search">
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </el-col>
        <!-- 添加按钮 -->
        <el-col :span="8" style="margin-left: 20px">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList" border style="width: 100%">
        <!-- 基本信息 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>

        <!-- 状态 -->
        <el-table-column label="状态">
          <template slot-scope="{row}">
            <el-switch v-model="row.mg_state" @change="userStateRequest(row)">
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作">
          <template slot-scope="{row}">
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="editUserById(row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteUserById(row.id)"></el-button>
            <!-- 设置按钮 -->
            <el-button type="warning" size="mini" icon="el-icon-s-tools" @click="toolsUserById(row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination style="text-align: center; margin-top: 20px" background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[3, 6, 9]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">>
      </el-pagination>
    </el-card>
    <!-- 添加用户页面 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email" type="email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户页面 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <el-form :model="editUserForm" :rules="editUserFormRules" ref="editUserFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email" type="email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限页面 -->
    <el-dialog title="分配权限" :visible.sync="toolsDialogVisible" width="50%" @close="toolsDialogClose">
      <p>当前用户：{{userinfo.username}}</p>
      <p>当前角色：{{userinfo.role_name}}</p>
      <p>
        分配新角色：
        <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="toolsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toolsRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as user from "network/user";
import * as rights from "network/rights";
import { checkEmail, checkMobile } from "./rules";

export default {
  name: "Users",
  components: {},
  data() {
    return {
      addDialogVisible: false, //添加的显示
      editDialogVisible: false, //修改的显示
      toolsDialogVisible: false, //分配的显示
      queryInfo: {
        query: "", //关键字
        pagenum: 1, // 当前页
        pagesize: 3, // 每页显示多少条数据
      },
      userList: [], //用户列表数据
      total: 0, //总条数
      userinfo: {}, // 需要被分配角色的用户信息
      rolesList: [], // 角色列表
      selectRoleId: "", // 分配角色时，当前选中的角色id
      //添加的数据
      addUserForm: {
        // 添加用户表单的数据
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //添加数据的验证
      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "长度需要在2到10之间", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度需要在6到15之间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      //修改的数据
      editUserForm: {
        // 添加用户表单的数据
        username: "",
        email: "",
        mobile: "",
      },
      //修改数据的验证
      editUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 2, max: 10, message: "长度需要在2到10之间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    //获取列表数据
    async getUserList() {
      let result = await user.getUserListRequest(this.queryInfo);
      if (result.status !== 200) {
        return this.alertMessage("获取用户列表失败", "error");
      }
      this.userList = result.data.data.users;
      this.total = result.data.data.total;
    },
    //监听pageSize改变的事件，并发送新的网络请求
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    //监听页码改变的事件，并发送新的网络请求
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    //搜索关键字
    search() {
      this.getUserList();
    },
    //更改状态
    async userStateRequest(row) {
      let result = await user.changUserStateRequest(row.id, row.mg_state);
      if (result.status !== 200) {
        return this.alertMessage("获取用户列表失败", "error");
      }
    },
    //修改用户
    async editUserById(id) {
      this.editDialogVisible = true;
      let result = await user.getUserByIdRequest(id);
      if (result.status !== 200) {
        return this.alertMessage("获取用户信息失败", "error");
      }
      this.editUserForm = result.data.data;
      console.log(this.editUserForm);
    },
    //删除用户
    deleteUserById(id) {
      this.$confirm("此操作将删除该该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let result = await removeUserByIdRequest(id);
          if (result.status !== 200) {
            return this.alertMessage("删除失败", "error");
          }
          this.alertMessage("删除成功", "success");
          this.getUserList();
        })
        .catch(() => {
          this.alertMessage("已取消删除", "info");
        });
    },
    //分配角色
    async toolsUserById(row) {
      this.toolsDialogVisible = true;
      this.userinfo = row;
      let result = await rights.getRolesListRequest();
      if (result.status !== 200) {
        return this.alertMessage("获取角色列表失败", "error");
      }
      this.rolesList = result.data.data;
    },
    //确定添加用户
    addUser() {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) return;
        let result = await user.addUserRequest(this.addUserForm);
        if (result.status !== 200) {
          return this.alertMessage("添加用户失败", "error");
        }
        this.alertMessage("添加用户成功", "success");
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    //确定修改用户
    editUser() {
      this.$refs.editUserFormRef.validate(async (valid) => {
        if (!valid) return;
        let result = await user.editUserByIdRequest(this.editUserForm);
        // 更新失败
        if (result.status !== 200) {
          return this.alertMessage("更新用户信息失败", "error");
        }
        this.alertMessage("更新用户信息成功", "success");
        this.editDialogVisible = false;
        this.getUserList();
      });
    },
    //确定分配角色
    async toolsRole() {
      if (!this.selectRoleId) {
        return this.alertMessage("请选择一个角色", "error");
      }
      let result = await user.allotNewRoleRequest(
        this.userinfo.id,
        this.selectRoleId
      );
      if (result.status !== 200) {
        return this.alertMessage("更新角色失败", "error");
      }
      this.alertMessage("更新角色成功", "success");
      this.toolsDialogVisible = false;
      this.getUserList();
    },
    //清除添加表单
    addDialogClose() {
      this.$refs.addUserFormRef.resetFields();
    },
    //清除修改表单
    editDialogClose() {
      this.$refs.editUserFormRef.resetFields();
    },
    //清除分配表单
    toolsDialogClose() {
      this.selectRoleId = "";
      this.userinfo = {};
    },
  },
};
</script>

<style scoped>
</style>
